//
//  BKUserRegisterViewController.m
//  bestkeep
//
//  Created by windCould on 16/11/28.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKUserRegisterViewController.h"
#import "BKCustextFieldView.h"
#import "BKMyCommon.h"
#import "BKUserRegisterProtocalController.h"
#import "BKUserUnitRequestAPI.h"
#import "BKUserInputNumView.h"
#import "BKUserModifyPwdView.h"
#import "BKUserCodeFormat.h"
#import "BKUserStatusInfo.h"
#import "BKAlertView.h"
@interface BKUserRegisterViewController ()<BKCustextFieldViewDelegate,UITextFieldDelegate,BKUserInputNumViewDelegate>

@property (nonatomic,strong)BKCustextFieldView * inputAccountView;
@property (nonatomic,strong)BKCustextFieldView * sMSVerificode;
@property (nonatomic,strong)BKCustextFieldView * secretCodeView;
@property (nonatomic,strong)BKUserModifyPwdView * modifyPwdView;
@property (nonatomic,strong)UIButton * registerBtn;
@property (nonatomic,strong)UILabel  * tipLab;
@property (nonatomic,strong)UIButton * protocalBtn;

@property (nonatomic,copy)NSString * imgCodeStr;
@property (nonatomic,copy)NSString * imgGernerStr;



@end

@implementation BKUserRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"手机快速注册";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpViews];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getImgCode:) name:@"getCode" object:nil];
}

#pragma mark ======================BKCustextFieldViewDelegate====================
-(void)custextFieldView:(BKCustextFieldView *)custextFieldView rightButtonTouch:(BKUserCustomBtn *)btn
{
    NSString *userNumStr = self.inputAccountView.textField.text;
    NSString *predictStr =  @"^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
    NSRegularExpression *regexCellphone = [NSRegularExpression regularExpressionWithPattern:predictStr options:0 error:nil];
    
    NSTextCheckingResult *isMatchCellphone = [regexCellphone firstMatchInString:userNumStr
                                                                        options:0
                                                                          range:NSMakeRange(0, [userNumStr length])];
    
    if (userNumStr.length == 0) {
        
        NSLog(@"请输入手机号码");
        btn.btnSelect = NO;
        [HUD showErrorMessage:@"请输入手机号码"];
        return;

    }
    
    if (!isMatchCellphone){
        
        NSLog(@"请输入正确的手机号码");
        [HUD showErrorMessage:@"请输入正确的手机号码"];
        btn.btnSelect = NO;
        return;
    }
    
    [self.view  endEditing:YES];
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI sendMessageWithMobileNum:self.inputAccountView.textField.text resultBlock:^(id obj, NSError *error) {
        
        [BKIndicationView dismiss];
        if (obj) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                NSLog(@"用户注册%@",result.msg);
                [HUD showSuccessMessage:result.msg];
                btn.btnSelect = YES;
                
            } else {
            
                NSLog(@"用户注册%@",result.msg);
                
                if ([result.code isEqualToString:@"-212401"]) {
                
                    BKAlertView *alert = [[BKAlertView alloc]initWithTitle:@"请输入验证码" BtnMessage:nil];
                    
                    __weak typeof(alert)walert = alert;
                    [alert addButton:Button_OK withTitle:@"确定" handler:^(BKAlertViewItem *item) {
                    
                        NSString *uuid;
                        self.imgCodeStr = walert.bk_textField.text;
                        
                        uuid = self.imgGernerStr;
                        
                        [self getMessageWithUserMobileNum:self.inputAccountView.textField.text imgCodeStr:walert.bk_textField.text imgCodeGenerationStr:uuid countDownBtn:btn];
                        
                    }];
                    
                    [alert show];
                
                } else {
                
                 [HUD showErrorMessage:result.msg];
                    
                }
                 btn.btnSelect = NO;
            }
            
        } else {
        
            NSLog(@"用户注册网络请求失败。。。");
            if (error.code==502) {
                [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
            }else{
                [HUD showErrorMessage:error.localizedDescription];
            }
             btn.btnSelect = NO;
        }
        
    }];
    
}


//获取图片验证码

-(void)getImgCode:(NSNotification *)notice
{
    self.imgGernerStr = notice.object;
}

-(void)getMessageWithUserMobileNum:(NSString *)mobileNum  imgCodeStr:(NSString *)imgCodeStr imgCodeGenerationStr:(NSString *)generationStr countDownBtn:(BKUserCustomBtn *)countDownBtn
{
   
    NSDictionary * dict = @{@"mobileNum":self.inputAccountView.textField.text,@"imgCodeStr":imgCodeStr};
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI getMessageCodeWithDataDict:dict imgCodeGenerationCode:generationStr block:^(id obj, NSError *error) {
        [BKIndicationView dismiss];
        if (obj) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                NSLog(@"用户注册%@",result.msg);
                [HUD showSuccessMessage:result.msg];
                countDownBtn.btnSelect = YES;
                
            } else {
                
                NSLog(@"用户注册%@",result.msg);
                
                if ([result.code isEqualToString:@"-212401"]) {
                    
                    BKAlertView *alert = [[BKAlertView alloc]initWithTitle:@"请输入验证码" BtnMessage:nil];
                    
                    __weak typeof(alert)walert = alert;
                    __weak typeof(self) weakSelf = self;
                    [alert addButton:Button_OK withTitle:@"确定" handler:^(BKAlertViewItem *item) {
                        
                        NSString *uuid;
                        weakSelf.imgCodeStr = walert.bk_textField.text;
                        
                        uuid = weakSelf.imgGernerStr;
                        
                        [self getMessageWithUserMobileNum:weakSelf.inputAccountView.textField.text imgCodeStr:weakSelf.imgCodeStr imgCodeGenerationStr:uuid
                                             countDownBtn:countDownBtn];
                        
                    }];
                    
                    [alert show];
                } else {
                
                    [HUD showErrorMessage:result.msg];
                    
                }
                
                countDownBtn.btnSelect = NO;
            }
            
        } else {
            
            NSLog(@"用户注册网络请求失败。。。");
            if (error.code==502) {
                [HUD showErrorMessage:@"服务器开小差了，请稍后再试！"];
            }else{
                [HUD showErrorMessage:error.localizedDescription];
            }
            countDownBtn.btnSelect = NO;
        }
        
    }];

}

#pragma mark =========================Function===================================

-(void)goToRegisterBtnClick
{
    [self.view endEditing:YES];
    BOOL result = [self isRightCorrectFormatDateWithMobileNum:self.inputAccountView.textField.text smsCode:self.sMSVerificode.textField.text pwdStr:self.modifyPwdView.contentTexfield.text secreatPwd:self.secretCodeView.textField.text];
    if (result) {
                    [BKIndicationView showInView:self.view];
                    [BKUserUnitRequestAPI
                         userRegisterWithAccount:self.inputAccountView.textField.text
                         pwdStr:self.modifyPwdView.contentTexfield.text
                         smsCodeStr:self.sMSVerificode.textField.text
                         secreatCode:self.secretCodeView.textField.text resultBlock:^(id obj, NSError *error) {
                             [BKIndicationView dismiss];
                             if (obj) {
                                 
                                 BKUserRequestResultModel * result = obj;
                                 if ([result.success isEqualToString:@"1"]) {
                                     
                                     NSLog(@"%@",result.msg);
                                     [HUD showSuccessMessage:result.msg];
                                     BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
                                     
                                     [userInfo.realm beginWriteTransaction];
                                     
                                     userInfo.userNum = self.inputAccountView.textField.text;
                                     [userInfo.realm commitWriteTransaction];
                                     
                                     [self.navigationController popViewControllerAnimated:YES];
                                     
                                 } else {
                                 
                                     NSLog(@"注册验证码通过%@",result.msg);
                                     [HUD showErrorMessage:result.msg];
                                 }
                                 
                             } else {
                             
                                 NSLog(@"注册验证通过网络请求失败。。。。。");
                                 [HUD showErrorMessage:@"网络请求失败"];
                             }
                    }];
        
                }
    
}

-(BOOL)isRightCorrectFormatDateWithMobileNum:(NSString *)mobileNum smsCode:(NSString *)smsCodeStr pwdStr:(NSString *)pwdStr secreatPwd:(NSString *)secreatPwd
{
   //判断是否为空
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:mobileNum]) {
    
        NSLog(@"请输入手机号码");
        [HUD showErrorMessage:@"请输入手机号码"];
        return NO;
    }
    
    
    if (![BKUserCodeFormat userMobileCodeOfBKPlatformatIsAdaptRequireWidthMobileNum:mobileNum]) {
        
        NSLog(@"请输入正确手机号码");
        [HUD showErrorMessage:@"请输入正确手机号码"];
        return NO;
    }
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:smsCodeStr]) {
        
        NSLog(@"请输入短信验证码");
        [HUD showErrorMessage:@"请输入短信验证码"];
        return NO;
    }
    
    if (![BKUserCodeFormat parameterValueIsNotNilAndZeroLengthWithContentStr:pwdStr]) {
        
        NSLog(@"请输入密码");
        [HUD showErrorMessage:@"请输入密码"];
        return NO;
    }
  
    if (![BKUserCodeFormat userPwdIsContainSpaceWithPwdStr:pwdStr]) {
        
        [HUD showErrorMessage:@"密码不能包含空格"];
    }
  //判定特殊格式
  
    if (![BKUserCodeFormat userPwdCodeFormatIsRigthWithUserPwdStr:pwdStr]) {
        
        NSLog(@"请输入正确的密码格式");
        [HUD showErrorMessage:@"请重新输入密码，英文或数字或 - _" ];
        return NO;
    }
   
    NSInteger num = [BKUserCodeFormat stringLengthIsRightWIthRequireMinLength:6 maxLength:18 contentStr:pwdStr];
    if (num == 6) {
        
        NSLog(@"密码必须位6-19位");
        [HUD showErrorMessage:@"密码不能少于6位"];
        return NO;
    }
    
    if (num == 18) {
        
        [HUD showErrorMessage:@"密码不能大于18位"];
        return NO;
    }
    
   
    return YES;
}


-(void)scanfRegisteBKMemmberProtocal
{
    BKUserRegisterProtocalController  * registerProtocal = [[BKUserRegisterProtocalController alloc]init];
    [self.navigationController pushViewController:registerProtocal animated:YES];
}

#pragma mark ====================BKUserInputNumViewDelegate===================
-(void)bKUserInputNumView:(BKUserInputNumView *)bKUserInputNumView btnSelect:(BOOL)isSelect
{

}

-(void)bKUserInputNumView:(BKUserInputNumView *)bKUserInputNumView inputTextFieldContent:(NSString *)content
{


}


#pragma mark =========================视图布局==================================

-(void)setUpViews{
    
    _inputAccountView = [[BKCustextFieldView alloc]initWithFrame:CGRectZero style:BKCustextFieldViewDefultType];
    _inputAccountView.placeHolderString = @"请输入手机号";
    _inputAccountView.textField.keyboardType = UIKeyboardTypeNumberPad;
    _inputAccountView.imgUrlStr = @"BK_My_butter_icon_02";
    [self.view addSubview:_inputAccountView];
    
    _sMSVerificode = [[BKCustextFieldView alloc]initWithFrame:CGRectZero style:BKCustextFieldViewTimeCountDownType];
    _sMSVerificode.myDlegate = self;
    _sMSVerificode.placeHolderString = @"请输入短信验证码";
    _sMSVerificode.textField.delegate = self;
    _sMSVerificode.imgUrlStr = @"BK_My_moblie_Message";
    [self.view addSubview:_sMSVerificode];
    
//    _inputPwdView = [[BKCustextFieldView alloc]initWithFrame:CGRectZero style:BKCustextFieldViewDefultType];
//    _inputPwdView.placeHolderString = @"请输入密码";
//    _inputPwdView.imgUrlStr = @"BK_My_butter_icon_03";
//    [self.view addSubview:_inputPwdView];
    
    _modifyPwdView = [[BKUserModifyPwdView alloc]initWithFrame:CGRectZero];
    _modifyPwdView.contentTexfield.placeholder = @"请输入密码";
    _modifyPwdView.contentTexfield.secureTextEntry = YES;
    _modifyPwdView.contentTexfield.delegate = self;
    _modifyPwdView.leftImgUrlStr = @"BK_My_butter_icon_03";
    _modifyPwdView.rightImgUrlStrs = @[@"BK_My_icon_eye",@"BK_My_icon_geye"];
    [self.view addSubview:_modifyPwdView];
    
    _secretCodeView = [[BKCustextFieldView alloc]initWithFrame:CGRectZero style:BKCustextFieldViewDefultType];
    _secretCodeView.placeHolderString = @"请输入暗号(选填)";
    _secretCodeView.textField.delegate = self;
    _secretCodeView.imgUrlStr = @"BK_My_butter_icon_08";
    [self.view addSubview:_secretCodeView];
    
    _registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _registerBtn.titleLabel.font = UIFontBoldCustom(18);
    [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    _registerBtn.layer.cornerRadius = 4;
    _registerBtn.layer.masksToBounds = YES;
    [_registerBtn addTarget:self action:@selector(goToRegisterBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _registerBtn.backgroundColor = BK_MY_COLOR_01;
    [self.view addSubview:_registerBtn];
    
    _tipLab = [[UILabel alloc]initWithFrame:CGRectZero];
    _tipLab.text = @"轻触上面的“注册”按钮，即表示你同意";
    _tipLab.textColor = HexColor(0xB2B2B2);
    _tipLab.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_tipLab];
    
    _protocalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_protocalBtn setTitle:@"BESTKEEP服务协议" forState:UIControlStateNormal];
    [_protocalBtn setTitleColor:HexColor(0x007AFF) forState:UIControlStateNormal];
    _protocalBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [_protocalBtn addTarget:self action:@selector(scanfRegisteBKMemmberProtocal) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_protocalBtn];
    
     [self layoutViews];
}

-(void)layoutViews{
    
    [_inputAccountView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view.mas_top).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(@(50));
    }];
    
    [_sMSVerificode mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_inputAccountView.mas_bottom).offset(0);
        make.left.mas_equalTo(_inputAccountView.mas_left).offset(0);
        make.right.mas_equalTo(_inputAccountView.mas_right).offset(0);
        make.height.mas_equalTo(@(50));
    }];

    [_modifyPwdView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_sMSVerificode.mas_bottom).offset(0);
        make.left.mas_equalTo(_inputAccountView.mas_left).offset(0);
        make.right.mas_equalTo(_inputAccountView.mas_right).offset(0);
        make.height.mas_equalTo(_inputAccountView.mas_height);
    }];
    
    [_secretCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_modifyPwdView.mas_bottom).offset(0);
        make.left.mas_equalTo(_inputAccountView.mas_left).offset(0);
        make.right.mas_equalTo(_inputAccountView.mas_right).offset(0);
        make.height.mas_equalTo(_inputAccountView.mas_height);
    }];
    
    
    [_registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
  
        make.top.mas_equalTo(_secretCodeView.mas_bottom).offset(20);
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(@(45));
    }];
    
    [_tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_registerBtn.mas_bottom).offset(8);
        make.centerX.mas_equalTo(_registerBtn.mas_centerX).offset(0);
        make.height.mas_equalTo(@(20));
    }];
    
    [_protocalBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_tipLab.mas_bottom).offset(5);
        make.centerX.mas_equalTo(_tipLab.mas_centerX).offset(0);
        make.size.mas_equalTo(CGSizeMake(200, 20));
    }];
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


@end
